package com.lframework.xingyun.sc.service.army;

import com.google.common.collect.Lists;
import com.lframework.xingyun.basedata.entity.ArmySaleOrder;
import com.lframework.xingyun.sc.entity.ArmySaleOrderAllVO;
import com.lframework.xingyun.sc.entity.ArmySaleOrderDaDuiVO;
import com.lframework.xingyun.sc.entity.ArmySaleOrderVO;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class ArmyConverter {
    public static List<ArmySaleOrderVO> convertOrderVOList(String ds, String customer, List<ArmySaleOrder> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }

        Map<String, List<ArmySaleOrder>> collect = list.stream().collect(Collectors.groupingBy(item -> item.getProductName() + item.getUnit()));
        List<ArmySaleOrderVO> res = new ArrayList<>();
        for (Map.Entry<String, List<ArmySaleOrder>> entry : collect.entrySet()) {
            ArmySaleOrderVO orderVO = new ArmySaleOrderVO();
            orderVO.setDs(ds);
            orderVO.setCustomer(customer);
            ArmySaleOrder armySaleOrder = entry.getValue().get(0);
            orderVO.setProductName(armySaleOrder.getProductName());
            orderVO.setNum(entry.getValue().stream().mapToDouble(item -> item.getNum().doubleValue()).sum());
            orderVO.setUnit(armySaleOrder.getUnit());
            res.add(orderVO);
        }
        Collections.sort(res, Comparator.comparing(ArmySaleOrderVO::getProductName));

        int i = 1;
        for (ArmySaleOrderVO orderVO : res) {
            orderVO.setSequence(i++);
        }

        return res;
    }

    public static List<ArmySaleOrderDaDuiVO> convertOrderDaDuiVOList(List<ArmySaleOrderAllVO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }
        Map<String, List<ArmySaleOrderAllVO>> collect = list.stream().collect(Collectors.groupingBy(item -> item.getProductName() + item.getUnit()));
        List<ArmySaleOrderDaDuiVO> res = new ArrayList<>();
        for (Map.Entry<String, List<ArmySaleOrderAllVO>> entry : collect.entrySet()) {
            ArmySaleOrderDaDuiVO orderVO = new ArmySaleOrderDaDuiVO();
            ArmySaleOrderAllVO armySaleOrder = entry.getValue().get(0);
            orderVO.setProductName(armySaleOrder.getProductName());

            orderVO.setUnit(armySaleOrder.getUnit());
            orderVO.setNum(entry.getValue().stream().mapToDouble(item -> item.getNum().doubleValue()).sum());
            orderVO.setPrice(armySaleOrder.getPrice());
            orderVO.setTaxRate(armySaleOrder.getTaxRate());

            res.add(orderVO);
        }
        Collections.sort(res, Comparator.comparing(ArmySaleOrderDaDuiVO::getTaxRate,  Comparator.nullsFirst(String::compareTo)));

        return res;
    }
}
